package com.jumi.microservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.RequestConstant;
import com.jumi.microservice.common.core.aspect.WebLog;
import com.jumi.microservice.common.utils.HttpRquestUtil;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.AreaInfoConfig;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.controller.base.BaseController;
import com.jumi.microservice.domain.FreightTemplateDO;
import com.jumi.microservice.domain.FreightTemplateDTO;
import com.jumi.microservice.domain.FreightTemplateExtendVO;
import com.jumi.microservice.domain.FreightTemplateVO;
import com.jumi.microservice.service.FreightTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 运费模板表 前端控制器
 * </p>
 *
 * @author liuz
 * @since 2020-07-27
 */
@RestController
@Api(tags = "运费模板表 相关接口")
@RequestMapping("/commodity/freight/template")
public class FreightTemplateController extends BaseController {

    @Autowired
    private FreightTemplateService freightTemplateService;

    @Autowired
    private AreaInfoConfig areaInfoConfig;


    @ApiOperation(value = "新增数据", notes = "新增一条运费模板表数据")
    @PostMapping("/add")
    @WebLog(description = "新增运费模板")
    public ResponseResult add(@RequestBody FreightTemplateVO freightTemplate, HttpServletRequest request) {
        FreightTemplateDTO dto = vo2Dto(freightTemplate);
        dto.setCreater(HttpRquestUtil.getUserName(request));
        dto.setModifier(HttpRquestUtil.getUserName(request));
        freightTemplateService.insert(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "删除数据", notes = "删除指定ID运费模板表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @DeleteMapping("/delete")
    @WebLog(description = "删除运费模板")
    public ResponseResult delete(@RequestParam Long id, HttpServletRequest request) {
        freightTemplateService.delete(id, HttpRquestUtil.getUserName(request));
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "更新数据", notes = "更新指定ID运费模板表数据")
    @PutMapping("/update")
    @WebLog(description = "更新运费模板")
    public ResponseResult update(@RequestBody FreightTemplateVO freightTemplate, HttpServletRequest request) {
        FreightTemplateDTO dto = vo2Dto(freightTemplate);
        dto.setModifier(HttpRquestUtil.getUserName(request));
        dto.setCreater(HttpRquestUtil.getUserName(request));
        freightTemplateService.updateFt(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "查询数据", notes = "获取指定ID运费模板表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<FreightTemplateVO> detail(@RequestParam Long id) {
        FreightTemplateDTO freightTemplate = freightTemplateService.selectById(id);
        return ResultGenerator.genSuccessResult(dto2Vo(freightTemplate));
    }


    @ApiOperation(value = "查询分页", notes = "获取运费模板表分页列表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页码"),
        @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/list")
    public BasePageResponse<List<FreightTemplateVO>> list(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            FreightTemplateVO freightTemplate) {
        LambdaQueryWrapper<FreightTemplateDO> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(freightTemplate.getTemplateName()), FreightTemplateDO::getTemplateName,freightTemplate.getTemplateName());
        wrapper.eq(FreightTemplateDO::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.orderByDesc(FreightTemplateDO::getId, FreightTemplateDO::getUpdateTime);
        IPage<FreightTemplateDO> pageInfo = freightTemplateService.page(
                new Page<>(page, size),wrapper);
        List<FreightTemplateVO> vos = pageInfo.getRecords().stream().map(p->{
            FreightTemplateVO vo = new FreightTemplateVO();
            vo.setId(p.getId());
            vo.setTemplateName(p.getTemplateName());
            vo.setCreateTime(p.getCreateTime());
            vo.setUpdateTime(p.getUpdateTime());
            vo.setModifier(p.getModifier());
            vo.setRule(p.getRule());
            //获取运费地区信息
            List<FreightTemplateExtendVO> freightTemplateExtendVOS = freightTemplateService.selectExtendsById(p.getId(), p.getRule());
            vo.setFreightTemplateExtendVO(freightTemplateExtendVOS);
            return vo;
        }).collect(Collectors.toList());
        return ResultGenerator.genSuccessResultPage(vos,pageInfo.getTotal());
    }

    @ApiOperation(value = "复制模板数据", notes = "复制指定ID运费模板表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @PostMapping("/cloneInfo")
    public ResponseResult cloneInfo(@RequestParam Long id, @RequestHeader(RequestConstant.ADMIN_NAME) String username) {
        freightTemplateService.cloneInfo(id, username);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "获取全部行政区信息", notes = "获取全部行政区信息")
    @GetMapping("/areaInfo")
    public ResponseResult areaInfo() {
        return ResultGenerator.genSuccessResult(areaInfoConfig);
    }

    /**
     * vo->dto
     * @param vo
     * @return
     */
    private FreightTemplateDTO vo2Dto(FreightTemplateVO vo){
        FreightTemplateDTO dto = null;
        try{
            dto = vo.clone(FreightTemplateDTO.class);
            dto.setFreightTemplateExtend(vo.getFreightTemplateExtendVO());
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return dto;
    }

    /**
     * dto->vo
     * @param dto
     * @return
     */
    private FreightTemplateVO dto2Vo(FreightTemplateDTO dto){
        FreightTemplateVO vo = null;
        try {
            vo = dto.clone(FreightTemplateVO.class);
            vo.setFreightTemplateExtendVO(dto.getFreightTemplateExtend());
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return vo;
    }
}
